<!-- 表格组件 -->
<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="请输入资料名称" style="width: 150px" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.operName" placeholder="请输入创建人" style="width: 150px" />
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- <el-date-picker v-model="entryDate" clearable value-format="yyyy-MM-dd HH:mm" type="datetimerange"
          placeholder="选择日期" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 360px"
          @change="handleDateChange" /> -->
        <el-select v-model="queryParams.term" placeholder="请选择学年" style="width: 150px">
          <el-option v-for="item in schoolyearList" :key="item.id" :value="item.term" :label="item.term" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExports"
        >导出</el-button>
      </el-form-item>
      <el-form-item>
        <el-upload
          ref="upload"
          class="upload-demo"
          :action="imports.url"
          :on-change="uploadChange"
          :file-list="fileList"
          :headers="imports.headers"
          :auto-upload="true"
          :multiple="true"
          :on-exceed="handleExceed"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
        >
          <el-button size="mini" type="primary" icon="el-icon-upload">上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="dialogVisible = true">批量删除</el-button>
      </el-col> -->
      <!--       <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
    </el-row>
    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="docu" :rules="rules" label-width="80px" size="mini">
        <el-form-item docu="name" label="资料名称" prop="name">
          <el-input v-model="docu.name" :disabled="docu.status == '1'" placeholder="请输入资料名称" style="width: 250px" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="docu.remark" :disabled="docu.status == '1'" placeholder="请输入备注" style="width: 250px" />
        </el-form-item>
        <el-form-item label="专业" prop="deptId">
          <treeselect v-model="form.majorId" :options="deptOptions" :show-count="true" placeholder="请选择专业" style="width: 250px" />
        </el-form-item>
        <el-form-item label="教师" prop="deptId">
          <treeselect v-model="form.majorId" :options="deptOptions" :show-count="true" placeholder="请选择教师" style="width: 250px" />
        </el-form-item>
        <el-form-item prop="appendix">
          <span slot="label"> 附件上传 </span>
          <el-radio-group v-model="docu.appendix" :disabled="docu.status == '1'">
            <el-radio key="0" label="0">禁用</el-radio>
            <el-radio key="1" label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="status">
          <span slot="label">
            <el-tooltip content="发布后不允许修改内容" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
            状态
          </span>
          <el-radio-group v-model="docu.status">
            <el-radio key="0" label="0">禁用</el-radio>
            <el-radio key="1" label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
            v-model="docu.endTime"
            clearable
            type="datetime"
            placeholder="选择时间"
            size="small"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" style="width: 50px" />
      <el-table-column prop="name" label="资料名称" align="center" show-overflow-tooltip width="170px" />
      <el-table-column prop="remark" label="备注" align="center" />
      <el-table-column prop="operName" label="创建人" align="center" />
      <el-table-column prop="majorId" label="专业" align="center" />
      <el-table-column prop="appendix" label="是否上传附件" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.appendix == 0">禁用</span>
          <span v-if="scope.row.appendix == 1">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="term" label="学年" align="center" />
      <el-table-column prop="state" label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">禁用</span>
          <span v-if="scope.row.status == 1">启用</span>
        </template> </el-table-column><el-table-column prop="endTime" label="截止时间" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.endTime
              ? parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}")
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="updateTime" label="更新时间" align="center" />
      <el-table-column :width="dynamicColumnWidth" label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.id)"
          >修改</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-folder-checked"
            @click="goto_screen(scope.row)"
          >筛选</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-monitor"
            @click="goto_control(scope.row)"
          >控制</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'user', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-pie-chart"
            @click="goto_data(scope.row)"
          >数据</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteById(scope.row.id)"
          >删除</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'user', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleExport(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, update, deleteById, add, query_docu } from '@/api/files.js'
import { list } from '@/api/schoolyear.js'
import { parseTime } from '@/utils'
import checkPermission from '@/utils/permission' // 权限判断函数
import { mapState, mapMutations } from 'vuex'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/user'
// import axios from 'axios'

// import axios from 'axios'

export default {
  components: { Treeselect },
  props: {
    user: {
      type: Object,
      default: () => ({}) // 设置一个空对象作为默认值
    }
  },
  data() {
    return {
      deptOptions: undefined,
      form: {},
      filename: '',
      imports: {
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/docu/import'
      },
      exports: {
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/docu/exports'
      },
      fileList: [], // 上传文件列表
      background: true,
      loading: false,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      schoolyearList: [],
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表单校验
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        endTime: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      queryParams: {
        name: '',
        operName: '',
        status: '',
        majorId: '',
        createTime: '', // 添加开始时间字段
        endTime: '', // 添加结束时间字段
        term: '',
        ids: []
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {},
      title: '',
      docu: {
        name: '',
        appendix: '0',
        remark: '',
        majorId: '',
        status: '0',
        endTime: undefined
      },
      createTime: '',
      endTime: '',
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      tableKey: 0,
      list: null,
      total: 0,
      input1: '',
      input2: '',
      update_name: '',
      update_remark: '',
      queryForm: {
        createTime: undefined,
        id: undefined,
        name: undefined,
        operName: undefined,
        majorId: undefined,
        remark: undefined,
        status: undefined
      },
      computed: {
        ...mapState(['name']),
        dynamicColumnWidth() {
          if (this.checkPermission(['user'])) {
            return '150px'
          } else {
            return '250px'
          }
        }
      }
    }
  },
  watch: {
    user: {
      handler(user) {
        if (user) {
          console.log(user)
          this.form = { id: user.id, name: user.name, phoneNumber: user.phoneNumber, email: user.email, sex: user.sex, majorId: user.majorId }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getDeptTree()
  },

  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
    this.getSchoolyear()
  },

  methods: {
    close() {
      this.$tab.closePage()
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    handleExports() {
      // 选中数据时下载选择数据
      if (this.multipleSelection.length > 0) {
        this.queryParams.ids = this.multipleSelection.map((item) => item.id) // 传递筛选后的id数组
        this.filename = '选中数据-' + new Date().getTime() + '.zip'
        // eslint-disable-next-line no-empty
      } else {
        this.queryParams.ids = [] // 传递空数组
        if (this.queryParams.name === '' && this.queryParams.operName === '' && this.queryParams.status === '' && this.queryParams.term === '') {
          this.filename = '全部数据-' + new Date().getTime() + '.zip'
          // eslint-disable-next-line no-empty
        } else {
          this.filename = '筛选数据-' + new Date().getTime() + '.zip'
        }
      }
      this.filename = '资料-' + new Date().getTime() + '.zip'
      this.download(this.exports.url, this.queryParams, this.filename)
    },
    uploadChange(file, fileList) {
      console.log(file.name, fileList)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleExceed(files, fileList) {
      this.$message.error('上传文件超出限制')
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.imports.isUploading = false
      this.fileName = response.data.fileName
      this.fileUrl = response.data.fileUrl
      this.$message({ message: '上传成功', type: 'success' })
      this.fileList = [] // 清空上传列表
      this.page() // 刷新页面
    },
    // 查询分页数据
    checkPermission,
    getSchoolyear() {
      list().then(res => {
        this.schoolyearList = res.data
      })
    },
    page() {
      // 初始化加载数据
      const requestData = {
        status: this.queryParams.status,
        operName: this.queryParams.operName,
        name: this.queryParams.name,
        state: this.queryParams.state,
        majorId: this.queryParams.majorId,
        createTime: this.queryParams.createTime,
        endTime: this.queryParams.endTime,
        current: this.current,
        pageSize: this.pageSize,
        appendix: this.queryParams.appendix, // 附件
        term: this.queryParams.term,
        pagesize: this.pageSize
      }

      page(requestData)
        .then((res) => {
          this.totalCount = res.data.total
          this.tableData = res.data.records
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    // 跳转界面
    goto_control(row) {
      this.$router.push({
        name: 'DataManage2',
        params: {
          id: row.id
        }
      }) // 根据路由名称跳转
    },
    // 跳转界面
    goto_screen(row) {
      this.$router.push({
        name: 'DataManage4',
        params: {
          id: row.id
        }
      }) // 根据路由名称跳转
    },
    // 跳转界面
    goto_data(row) {
      if (row.status !== '1') {
        this.$message({
          message: '资料未发布',
          type: 'error'
        })
        return
      }
      this.$router.push({
        name: 'DataManage3',
        params: {
          id: row.id
        }
      }) // 根据路由名称跳转
    },
    handleAdd() {
      this.dialogVisible = true
      this.reset()
    },
    // 表单重置
    reset() {
      this.docu = {
        name: '',
        appendix: '0',
        remark: '',
        status: '0',
        majorId: '',
        operName: '',
        endTime: undefined,
        entryDate: []
      }
    },
    add() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let operator

          if (this.docu.id) {
            // 修改
            operator = update(this.docu)
          } else {
            operator = add(this.docu)
          }

          operator.then((resp) => {
            if (resp.code == '1') {
              this.dialogVisible = false
              this.page()
              this.$message({ message: '保存成功', type: 'success' })
            } else {
              this.$message.error(resp.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除资料
    deleteById(id) {
      console.log('aaaaaaaaaaa:', id)
      this.$confirm('此操作将删除该资料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 2. 发送AJAX请求
          deleteById(id).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.selectedIds = val.map((item) => item.id)
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = [] // 清除时间范围
      this.queryParams.operName = ''
      this.queryParams.name = ''
      this.queryParams.majorId = ''
      this.queryParams.createTime = ''
      this.queryParams.endTime = ''
      this.page()
    },
    // 修改资料
    handleUpdate(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      query_docu(id).then((res) => {
        this.docu = res.data
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    /** 导出按钮操作 */
    handleExport(row) {
      this.$confirm('是否下载所有数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 压缩包下载路径
          const downloadUrl =
            process.env.VUE_APP_BASE_API + 'data/export/' + row.id
          const fileName = `${row.name + '-' + new Date().getTime()}.zip`

          // 调用下载方法
          this.download(downloadUrl, { method: 'POST' }, fileName)
        })
        .catch(() => {
          this.$message.info('已取消导出')
        })
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}

.fixed-width {
  min-width: 200px;
  max-width: 250px;
}

</style>
